#!/usr/bin/env python3
"""
数据库初始化脚本
用于创建数据库表和初始化数据
"""

import asyncio
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.database.database import async_engine
from src.database.base import Base
from src.models import user  # 导入所有模型
from src.service.user_service import UserService
from src.schemas.user import UserCreate
from src.database.database import AsyncSessionLocal


async def create_tables():
    """创建数据库表"""
    print("正在创建数据库表...")
    async with async_engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    print("数据库表创建完成!")


async def create_admin_user():
    """创建管理员用户"""
    print("正在创建管理员用户...")
    
    async with AsyncSessionLocal() as db:
        # 检查是否已存在管理员用户
        existing_admin = await UserService.get_user_by_username(db, "admin")
        if existing_admin:
            print("管理员用户已存在，跳过创建")
            return
        
        # 创建管理员用户
        admin_data = UserCreate(
            username="admin",
            password="admin123",
            nick_name="系统管理员",
            email="admin@capcut.com",
            remark="系统默认管理员账户"
        )
        
        try:
            admin_user = await UserService.create_user(db, admin_data)
            print(f"管理员用户创建成功: {admin_user.username}")
        except Exception as e:
            print(f"创建管理员用户失败: {e}")


async def create_test_user():
    """创建测试用户"""
    print("正在创建测试用户...")
    
    async with AsyncSessionLocal() as db:
        # 检查是否已存在测试用户
        existing_user = await UserService.get_user_by_username(db, "test")
        if existing_user:
            print("测试用户已存在，跳过创建")
            return
        
        # 创建测试用户
        test_data = UserCreate(
            username="test",
            password="test123",
            nick_name="测试用户",
            email="test@capcut.com",
            remark="系统测试账户"
        )
        
        try:
            test_user = await UserService.create_user(db, test_data)
            print(f"测试用户创建成功: {test_user.username}")
        except Exception as e:
            print(f"创建测试用户失败: {e}")


async def main():
    """主函数"""
    print("开始初始化数据库...")
    
    try:
        # 创建数据库表
        await create_tables()
        
        # 创建初始用户
        await create_admin_user()
        await create_test_user()
        
        print("数据库初始化完成!")
        
    except Exception as e:
        print(f"数据库初始化失败: {e}")
        sys.exit(1)
    
    finally:
        # 关闭数据库连接
        await async_engine.dispose()


if __name__ == "__main__":
    asyncio.run(main()) 